import results
from table import *
from pprint import pprint

class Num:
   def __init__(self,lessIsMore=True):
       self.lessIsMore = lessIsMore
       self.min=    10**32
       self.max=-1* 10**32
   def put(self,n) :
       self.min = min(n,self.min)
       self.max = max(n,self.max)
       return n
   def __str__(self) :
       return str({'min':self.min,'max':self.max,'lessIsMore':self.lessIsMore})
   def normalize(self,n):
       if (self.max - self.min == 0): tmp = 0
       else: tmp = (n - self.min) / (self.max - self.min)
       return 1 - tmp if self.lessIsMore else tmp
           
def distance2Heaven(nums,headers) :
    "returns a number 0..1 and more is better"
    u = [header.normalize(num)**2 for num,header in zip(nums,headers)]
    return   sum(u)**0.5/len(u)**0.5 

def aggregate(experiments,headers) :
    out=[]
    for _,objectives in experiments:
        for i,objective in enumerate(objectives):
            headers[i].put(objective)
    
    for decisions,objectives in experiments:
        tmp = decisions + [distance2Heaven(objectives,headers)]        
        out += [tmp]
    return out
 
def joesPayDiscretizer(val):
    if val <= 19: return 1
    elif val <= 29: return 2
    elif val <= 40: return 3
    else:  return -1
    
def joesPriDiscretizer(val):
    if val <= 3: return 1
    elif val <= 7: return 2
    elif val <= 10: return 3
    else: return -1
    
def readJoe(data):
   headers = [Num(),Num(), Num(),Num(),Num(), Num()]
   names   = ['$m1','$m2','$m3','$m4','$m5','$class']
   data    =  aggregate(data,headers)
   t       = Table()
   t.header(names)
   score = []
   for row in data: t.cells(row)
   for i,row in enumerate(data):
       for j,col in enumerate(row):
           data[i][j] = joesPayDiscretizer(col)
       score.append(row[5])
   #t.complete()
   return t,score
   
@demo
def joeread1():
   pprint(readJoe(results.data).data)
